package com.mingqijia.gassafety.console.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gap.basic.base.CommonResponse;
import com.gap.basic.exception.BizException;
import com.github.pagehelper.util.StringUtil;
import com.mingqijia.gassafety.db.entity.Dictionary;
import com.mingqijia.gassafety.db.entity.Dtu;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.mingqijia.gassafety.shared.constant.OperateRecordEnum;
import com.mingqijia.gassafety.shared.constant.PageColumnConst;
import com.mingqijia.gassafety.shared.utils.HeaderUtil;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageColumns;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.*;
import com.mingqijia.gassafety.webserver.response.*;
import com.mingqijia.gassafety.webserver.service.EquipmentService;
import com.mingqijia.gassafety.shared.log.LogRecord;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import static com.mingqijia.gassafety.shared.constant.Constants.BIND_CHANNEL_ASST;
import static com.mingqijia.gassafety.shared.constant.Constants.BIND_CHANNEL_GAS;
import static com.mingqijia.gassafety.shared.constant.PageColumnConst.*;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName DeviceController.java
 * @createTime 2022年02月21日
 */
@RestController
@Api(tags = "业务-设备管理")
@RequestMapping("/business/v1/equipment")
public class EquipmentController {


    @Autowired
    HeaderUtil headerUtil;


    @Autowired
    DtuMapper dMapper;
    @Autowired
    private EquipmentService equipmentService;
    @Value(value = "${gassafety.installationPosition.checkSwitch}")
    private boolean checkSwitch = true;

    /**
     * 新增设备信息
     *
     * @param request
     * @return
     */
    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_16, commonInfo = "#request.imei")
    @PostMapping("saveEquipment")
    @ApiOperation(value = "新增设备信息")
    public CommonResponse<Object> saveDevice(@RequestBody @Valid
                                                     SaveDeviceRequest request) {
        equipmentService.saveDevice(request);
        return CommonResponse.success(null);
    }

    /**
     * 编辑设备信息
     *
     * @param request
     * @return
     */
    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_18, commonInfo = "#request.imei",detail = "'【设备号：' + #request.imei + '】\n'")
    @PostMapping("editEquipment")
    @ApiOperation(value = "编辑设备信息")
    public CommonResponse<Object> editEquipment(@RequestBody @Valid EditDeviceRequest request) {
        equipmentService.editEquipment(request);
        return CommonResponse.success(null);
    }


    /**
     * 设备信息详情
     *
     * @return
     */
    @GetMapping("equipmentInfo")
    @ApiOperation(value = "设备信息详情")
    public CommonResponse<DtuInfoResponse> equipmentInfo(@RequestParam("equipmentId")
                                                         @ApiParam(value = "设备id") String equipmentId) {
        return CommonResponse.success(equipmentService.equipmentInfo(equipmentId));
    }


    /**
     * 设备删除
     *
     * @return
     */
    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_19)
    @PostMapping("equipmentDelete")
    @ApiOperation(value = "设备删除")
    public CommonResponse<Object> equipmentDelete(@RequestBody @Valid DeleteRequest request) {
        equipmentService.equipmentDelete(request.getEquipmentIds());
        return CommonResponse.success(null);
    }


    /**
     * 设备列表筛选
     *
     * @return
     */
    @PostMapping("equipmentList")
    @ApiOperation(value = "设备列表筛选")
    public CommonResponse<PageUtil<DtuListResponse>> equipmentList(@RequestBody @Valid EquipmentListRequest request) {
        return CommonResponse.success(equipmentService.equipmentList(request));
    }
    /**
     * 设备列表筛选
     *
     * @return
     */
    @PostMapping("detectors")
    @ApiOperation(value = "根据控制器imei查询点位数据")
    public CommonResponse<List<Map<String, Object>>> detectors(@RequestBody @Valid DetectorRequest request) {
        return CommonResponse.success(equipmentService.detectors(request));
    }

    /**
     * 设备excel导入
     *
     * @return
     */
    @PostMapping("import")
    @ApiOperation(value = "设备excel导入")
    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_17)
    public CommonResponse<Object> importData(@ApiParam(value = "file") MultipartFile file) {
        String message= equipmentService.importData(file);
        if (!StringUtils.isEmpty(message)) return CommonResponse.failure(message);
        return CommonResponse.success(null);
    }


    /**
     * 字典设备数据映射列表
     * type：null 查询设备相关全部映射
     *
     * @return
     */
    @GetMapping("dictMap")
//    @ApiOperation(value = "字典设备数据映射列表")
    public CommonResponse<Object> dictMap(@RequestParam(value = "type", required = false) String type) {
        return CommonResponse.success(equipmentService.dictMap(type, null, ""));
    }



    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_12, detail =
            "'【设备号：'+ #request.imei + '】\n'")
    @PostMapping("/editName")
    @ApiOperation(value = "编辑设备名")
    public CommonResponse<Object> editName(@RequestBody @Valid EquipmentPositionRequest request) {
        equipmentService.editEquipmentName(request);
        return CommonResponse.success("success");
    }

    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_55, detail =
            "'【设备号：'+ #request.imei + '】\n'")
    @PostMapping("/editInstallDate")
    @ApiOperation(value = "编辑设备安装日期")
    public CommonResponse<Object> editInstallDate(@RequestBody @Valid EquipmentPositionRequest request) {
        equipmentService.editInstallDate(request);
        return CommonResponse.success("success");
    }



    @PostMapping("/editInstallationAddress")
    @ApiOperation(value = "编辑设备安装地址")
    public CommonResponse<Object> editInstallationAddress(@RequestBody @Valid EquipmentAddressRequest request) {
        equipmentService.editInstallationAddress(request);
        return CommonResponse.success("success");
    }

    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_11, detail =
            "'【设备号：' + #request.imei + '】\n'")
    @ApiOperation(value = "编辑设备安装位置")
    @PostMapping("/editPosition")
    public CommonResponse<Object> editPosition(@RequestBody @Valid EquipmentPositionRequest request) {
        if (checkSwitch) {
            if (StringUtil.isEmpty(request.getInstallationPosition())) {
                throw new BizException("请填写安装位置");
            }
        }
        equipmentService.editPosition(request);
        return CommonResponse.success("success");

    }

    @PostMapping("/dictMapOpt")
    public CommonResponse<Object> dictMapOpt(@RequestBody @Valid Dictionary dictionary) {
        equipmentService.dictMapOpt(dictionary);
        return CommonResponse.success("success");

    }

    /**
     * 绑定记录列表
     *
     * @return
     */
    @PostMapping("bindingHistory")
    @ApiOperation(value = "绑定记录列表")
    public CommonResponse<PageUtil<ConsumerDtuHistoryResponse>> bindingHistory(@RequestBody @Valid ConsumerDtuHistoryRequest request) {
        return CommonResponse.success(equipmentService.bindingHistory(request));
    }


    @PostMapping("bindEquipmentList")
    @ApiOperation(value = "设备关联-设备列表筛选")
    public CommonResponse<PageUtil<DtuListResponse>> bindEquipmentList(@RequestBody @Valid EquipmentListRequest request) {
        return CommonResponse.success(equipmentService.bindEquipmentList(request));
    }


    @ApiOperation(value = "客户详情-设备列表筛选")
    @PostMapping("/consumerEquipment")
    public CommonResponse<Object> consumerEquipment(@RequestBody @Valid ComsumerEquipmentRequest request) {
        request.setTemplateType(headerUtil.getTemplateType());

        //查询设备来源
        QueryWrapper<Dtu> query = new QueryWrapper<>();
        query.lambda().or().eq(Dtu::getIsDeleted, 0)
                .eq(Dtu::getConsumerId, request.getConsumerId());
        List<Dtu> dtus = dMapper.selectList(query);
        Integer from = 0;
        if (!CollectionUtils.isEmpty(dtus)) {
            from = dtus.get(0).getEquipmentFrom();
            List<Dtu> dtuList = dtus.stream()
                    .filter(dtu -> !dtu.getIMEI().contains("-"))
                    .collect(Collectors.toList());
            if (dtuList.size() == 0 || dtuList.size() == 1) {
                request.setIsDeleteConsumer("Y");
            }else {
                request.setIsDeleteConsumer("N");
            }
        }else {
            request.setIsDeleteConsumer("Y");
        }
        if (BIND_CHANNEL_ASST == request.getTemplateType()) {

            if(from==0){
                return CommonResponse.success(equipmentService.consumerEquipmentAsst(request));
            }else {
                return CommonResponse.success(equipmentService.consumerEquipment(request));
            }
        } else if (BIND_CHANNEL_GAS == request.getTemplateType()) {
            return CommonResponse.success(equipmentService.consumerEquipment(request));
        }


        return CommonResponse.failure("模板类型错误");
    }


    @ApiOperation(value = "客户维度-设备绑定解绑历史")
    @PostMapping("/consumerBindingHistory")
    public CommonResponse<Object> consumerBindingHistory(@RequestBody @Valid ConsumerBindingHistoryRequest request) {
        request.setTemplateType(headerUtil.getTemplateType());
        PageUtil<ConsumerBindingHistoryResponse> response = equipmentService.consumerBindingHistory(request);
        if (BIND_CHANNEL_ASST == request.getTemplateType()) {
            response.setColumns(PageColumnConst.add(asstConsumerBindingHistoryTitles, asstConsumerBindingHistoryIndices));
        } else if (BIND_CHANNEL_GAS == request.getTemplateType()) {
            response.setColumns(PageColumnConst.add(gasConsumerBindingHistoryTitles, gasConsumerBindingHistoryIndices));

        }
        return CommonResponse.success(response);
    }


    @ApiOperation(value = "设备型号")
    @GetMapping("/equipmentModels")
    public CommonResponse<List<String>> equipmentModels(@RequestParam("manufacturer") String manufacturer) {

        return CommonResponse.success(equipmentService.equipmentModels(manufacturer));
    }

    /**
     * 设备删除excel导入
     *
     * @return
     */
    @PostMapping("/deviceDelete/import")
    @ApiOperation(value = "设备删除excel导入")
    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_80)
    public CommonResponse<Object> deviceImportData(@ApiParam(value = "file") MultipartFile file) {
        String message= equipmentService.deviceImportData(file);
        if (!StringUtils.isEmpty(message)) return CommonResponse.failure(message);
        return CommonResponse.success(null);
    }

}
